class Assistance < ActiveRecord::Base
  
  belongs_to :client
  belongs_to :operator
  has_and_belongs_to_many :operations, :association_foreign_key => "operation_id", :join_table => "operations_assistances"
  
  validates_presence_of :operator_id, :client_id
  validates_numericality_of :token, :unless => Proc.new { |t| t.token.blank? || t.token.nil? }
  
  # METODI STATO ASSISTENZA #
  
  def urgency_to_s
    return urgenza = case
      when urgency.zero?: "Non Tassativa"
      when urgency == 1: "Tassativa"
    end
  end
  
  def stato_to_s
    return stato = case 
            when ticket_state.zero?: "Incompleta" 
            when ticket_state == 1: "Parziale"
            when ticket_state == 2: "Completata"
    end
  end
  
  def stato_to_image
    return stato = case 
            when ticket_state.zero?: "flag_red.gif" 
            when ticket_state == 1: "flag_orange.gif"
            when ticket_state == 2: "flag_green.gif"
    end
  end
  
  def stato_to_color
    return stato = case 
            when ticket_state.zero?: "red" 
            when ticket_state == 1: "orange"
            when ticket_state == 2: "green"
    end
  end
  
  # METODI RESOCONTO ASSISTENZA #

  def confirm_to_s
    return conferma = case
      when confirm.zero?: "Non inviato"
      when confirm == 1: "Inviato"
    end
  end

  # METODI CALCOLO TEMPISTICHE ASSISTENZA #

  def scaduta?
    expiration < Time.now && ticket_state != 2
  end

  def execution_to_s
    if execution && ticket_state == 2
      execution.to_s(:short)
    else
      "Non definita"
    end
  end
  
  def expiration_to_s
    return expiration ? expiration.to_s(:short) : "Non definita"
  end

  def expiration_from_now
    if expiration != nil
      diff = (expiration - Time.now).abs

      days, dayfrac = diff.divmod(1.day)
      hours, hrfrac = dayfrac.divmod(1.hour)
      mins, secs = hrfrac.divmod(1.minute)
      
      if days >= 7
         return "più di 7gg"
      else
         result = []
         result << days.to_s + "gg," unless days.zero?
         result << "%02d:%02d" % [ hours, mins ]
         return result.join(' ')
      end
    end
  end
 
  def duration_to_s
    return duration ? duration.strftime("%H:%M") : "Non definita"
  end
  
  def token_to_s
    token ? token : "Non definito"
  end

end
